package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

import util.Debug;

public class DBConnection {
	private static ResourceBundle host = ResourceBundle.getBundle("Connection");	
	private static String DB_HOST = host.getString("DB_HOST").trim();
	private static String DB_NAME = host.getString("DB_NAME").trim();
	private static String DB_USER = host.getString("DB_USER").trim();
	private static String DB_PASSWORD = host.getString("DB_PASSWORD").trim();
		
		
    private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DB_URL = "jdbc:mysql://" + DB_HOST + "/" + DB_NAME;
    
    private static Connection connection;
    
    private DBConnection() {
    	connection = newConnection();
    }
    
    /* Refactoring > Singleton */
    public static synchronized Connection getInstance() {
    	if (connection == null) {
    		new DBConnection();
    	}
        return connection;
    }
    
    private Connection newConnection() {
    	Connection con = null;
    	loadDriver();
    	
        try {
        	con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
//        	System.out.println("Connection created successfully");
        	Debug.log(this, "newConnection()", "Connection created successfully");
        }
        catch (SQLException e) {                
            e.printStackTrace();
        }
        return con;
    }
    
    private void loadDriver()
    {
    	
    	try {
            Class.forName(DB_DRIVER);
//            System.out.println("Driver loaded successfully");
            Debug.log(this, "loadDriver()", "Driver loaded successfully");
        } catch(ClassNotFoundException cnfe) {
        	cnfe.printStackTrace();
        }
    }
    
//    public static void main(String[] args) {
//		Connection connection = DBConnection.getInstance();
//	}
}
